package com.jackstraw.jack_base.job.xxljob.config;

import com.jackstraw.jack_base.job.xxljob.aspect.annotation.XxlJobHandler;
import com.jackstraw.jack_base.job.xxljob.bean.ExecutorParam;
import com.jackstraw.jack_base.util.CollectionUtil;
import com.jackstraw.jack_base.util.JsonUtil;
import com.jackstraw.jack_base.util.StringUtil;
import com.jackstraw.jack_base.util.SpringUtil;
import com.xxl.job.core.executor.XxlJobExecutor;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import com.xxl.job.core.handler.IJobHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.Map;


@Slf4j
@Order(0)
@Configuration
public class XxlJobConfiguration implements InitializingBean {


    private ApplicationContext applicationContext;


    public XxlJobConfiguration(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        SpringUtil.setApplicationContextJack(applicationContext);
    }

    @Bean
    @ConditionalOnMissingBean(value = XxlJobExecutor.class)
    @ConfigurationProperties(prefix = "jack.job.xxljob")
    public XxlJobSpringExecutor xxlJobExecutor() {
        log.info(">>>>>>>>>>> xxl-job config init.");
        return new XxlJobSpringExecutor();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(XxlJobHandler.class);
        if (CollectionUtil.MapUtil.isEmpty(beansWithAnnotation)) {
            return;
        }

        beansWithAnnotation.values().stream().forEach(iJobHandler -> {
            if (iJobHandler instanceof IJobHandler) {
                XxlJobHandler xxlJobHandler = iJobHandler.getClass().getAnnotation(XxlJobHandler.class);
                String jobHandlerName = xxlJobHandler.jobHandlerName();
                if (StringUtil.StringUtilsBylang3.isEmpty(jobHandlerName)) {
                    throw new RuntimeException("xxl-job jobhandler[" + jobHandlerName + "] naming conflicts.");
                }
                XxlJobSpringExecutor.registJobHandler(jobHandlerName, (IJobHandler) iJobHandler);
                log.info("xxl-job jobhandler[{}]regist success", jobHandlerName);
            }
        });

    }

    public static void main(String[] args) {
        ExecutorParam<String> executorParam = new ExecutorParam<>();
        executorParam.setTenantName("damo");
        executorParam.setParam("aaa");

        String beanToJson = JsonUtil.getBeanToJson(executorParam);
        System.out.println(beanToJson);

    }
}
